import React, { useState } from 'react';
import axios from 'axios';

interface TransactionFormProps {
  className?: string;
}

// 交易记录类型定义
interface Transaction {
  id: string;
  date: string;
  amount: number;
  category: string;
  description: string;
  type: 'expense' | 'income';
  mood: string;
}

const TransactionForm: React.FC<TransactionFormProps> = ({ className = '' }) => {
  // 定义表单数据类型
  type FormData = {
    date: string;
    amount: string;
    category: string;
    description: string;
    type: 'expense' | 'income';
    mood: string;
  }

  // 初始化表单状态
  const [form, setForm] = useState<FormData>({
    date: '',
    amount: '',
    category: '',
    description: '',
    type: 'expense', // 默认以expense开始
    mood: ''
  });

  // 查询功能相关状态
  const [queryDate, setQueryDate] = useState<string>('');
  const [queryResults, setQueryResults] = useState<Transaction[]>([]);
  const [showResults, setShowResults] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [queryError, setQueryError] = useState<string>('');

  // 处理表单输入变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const response = await axios.post(`${process.env.REACT_APP_API}/transactions`, {
        ...form,
        amount: parseFloat(form.amount), // 从string转换为浮点数
        date: new Date(form.date).toISOString() // 将日期转换为ISO格式
      });
      alert("提交成功：" + JSON.stringify(response.data));
    } catch (err) {
      alert("提交失败：" + err);
    }
  };

  // 处理日期查询
  const handleDateQuery = async () => {
    if (!queryDate) {
      setQueryError('请选择日期');
      return;
    }

    setIsLoading(true);
    setQueryError('');

    try {
      const response = await axios.get(`${process.env.REACT_APP_API}/transactions/by-date`, {
        params: { date: new Date(queryDate).toISOString().split('T')[0] }
      });
      console.log("查询结果：", response.data);
      
      setQueryResults(response.data);
      setShowResults(true);
      setIsLoading(false);
    } catch (err) {
      console.error("查询失败：", err);
      setQueryError(err instanceof Error ? err.message : '查询失败，请稍后重试');
      setIsLoading(false);
    }
  };

  // 关闭结果显示
  const handleCloseResults = () => {
    setShowResults(false);
  };

  // 格式化日期显示 YYYY-MM-DD 格式为 YYYY年MM月DD日
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };

  return (
    <div className={`bg-white bg-opacity-80 p-8 rounded-xl shadow-lg w-full max-w-md ${className}`}>
      <h2 className="text-2xl font-bold text-center mb-4">PayRecordTiny</h2>
      
      <div className="space-y-3">
        <input 
          type="date" 
          name="date" 
          value={form.date} 
          onChange={handleChange}
          className="w-full border border-gray-300 rounded p-2" 
        />
        <input 
          name="amount" 
          placeholder="金额" 
          value={form.amount} 
          onChange={handleChange}
          className="w-full border border-gray-300 rounded p-2" 
        />
        <input 
          name="category" 
          placeholder="分类" 
          value={form.category} 
          onChange={handleChange}
          className="w-full border border-gray-300 rounded p-2" 
        />
        <input 
          name="description" 
          placeholder="描述" 
          value={form.description} 
          onChange={handleChange}
          className="w-full border border-gray-300 rounded p-2" 
        />
        <select 
          name="type" 
          value={form.type} 
          onChange={handleChange}
          className="w-full border border-gray-300 rounded p-2"
        >
          <option value="expense">支出</option>
          <option value="income">收入</option>
        </select>
        <input 
          name="mood" 
          placeholder="心情" 
          value={form.mood} 
          onChange={handleChange}
          className="w-full border border-gray-300 rounded p-2" 
        />
      </div>

      <button 
        onClick={handleSubmit}
        className="w-full mt-6 bg-blue-500 text-white py-2 rounded-lg hover:bg-blue-600 transition duration-200"
      >
        提交
      </button>

      {/* 查询功能区域 */}
      <div className="mt-8 pt-6 border-t border-gray-300">
        <h3 className="text-lg font-semibold mb-3">查询日期记录</h3>
        
        <div className="flex space-x-2">
          <input
            type="date"
            value={queryDate}
            onChange={(e) => setQueryDate(e.target.value)}
            className="flex-grow border border-gray-300 rounded p-2"
          />
          <button
            onClick={handleDateQuery}
            disabled={isLoading}
            className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition duration-200 disabled:bg-green-300"
          >
            {isLoading ? '查询中...' : '查询'}
          </button>
        </div>
        
        {queryError && (
          <p className="text-red-500 mt-2 text-sm">{queryError}</p>
        )}
      </div>

      {/* 查询结果展示 */}
      {showResults && (
        <div className="mt-4 bg-white rounded-lg shadow p-4 border border-gray-200">
          <div className="flex justify-between items-center mb-3">
            <h4 className="font-medium text-lg">
              {queryDate ? formatDate(queryDate) : '当日'}记录
            </h4>
            <button
              onClick={handleCloseResults}
              className="text-gray-500 hover:text-gray-700"
            >
              ✕
            </button>
          </div>
          
          {queryResults.length === 0 ? (
            <p className="text-gray-500 text-center py-4">当日无记录</p>
          ) : (
            <div className="space-y-3 max-h-64 overflow-y-auto">
              {queryResults.map((transaction) => (
                <div 
                  key={transaction.id} 
                  className={`p-3 rounded-md ${
                    transaction.type === 'expense' ? 'bg-red-50' : 'bg-green-50'
                  }`}
                >
                  <div className="flex justify-between">
                    <span className="font-medium">{transaction.category}</span>
                    <span className={transaction.type === 'expense' ? 'text-red-500' : 'text-green-500'}>
                      {transaction.type === 'expense' ? '-' : '+'}{transaction.amount}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600 mt-1">{transaction.description}</p>
                  <div className="text-xs text-gray-500 mt-1 flex justify-between">
                    <span>心情: {transaction.mood}</span>
                    <span>{new Date(transaction.date).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {queryResults.length > 0 && (
            <div className="mt-3 pt-3 border-t border-gray-200">
              <div className="flex justify-between text-sm">
                <span>总记录数:</span>
                <span>{queryResults.length}条</span>
              </div>
              <div className="flex justify-between font-medium mt-1">
                <span>总支出:</span>
                <span className="text-red-500">
                  ¥{queryResults
                    .filter(t => t.type === 'expense')
                    .reduce((sum, t) => sum + t.amount, 0)
                    .toFixed(2)}
                </span>
              </div>
              <div className="flex justify-between font-medium mt-1">
                <span>总收入:</span>
                <span className="text-green-500">
                  ¥{queryResults
                    .filter(t => t.type === 'income')
                    .reduce((sum, t) => sum + t.amount, 0)
                    .toFixed(2)}
                </span>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default TransactionForm;